/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tos.pip;

/**
 *
 * @author Milos
 */
public class Skladiste {

    private static int ukId = 0;
    private int id = ++ukId;
    private int[] niz;
    private int ulaz, izlaz;
    private int pun;

    public Skladiste(int kapacitet) {
        niz = new int[kapacitet];
    }

    public synchronized void stavi(int podatak) throws InterruptedException {
        while (pun == niz.length) {
            wait();
        }
        niz[ulaz] = podatak;
        ulaz++;
        if (ulaz == niz.length) {
            ulaz = 0;
        }
        pun++;
        notifyAll();
    }

    public synchronized int uzmi(boolean exit) throws InterruptedException {
        if (exit == false) {
            while (pun == 0) {
                wait();
            }
            int podatak = niz[izlaz];
            izlaz++;
            if (izlaz == niz.length) {
                izlaz = 0;
            }
            pun--;
            notifyAll();
            return podatak;
        } else {
            if (pun == 0) {
                return -1;
            }
            int podatak = niz[izlaz];
            izlaz++;
            if (izlaz == niz.length) {
                izlaz = 0;
            }
            pun--;
            notifyAll();
            return podatak;

        }
    }

    public synchronized String toString() {
        String text = "Skladiste " + id + ": ";
        for (int i = 0; i < pun; i++) {
            text += "" + niz[(izlaz + 1) % niz.length] + " ";
        }

        return text;
    }
}
